package com.example.logicalthinking.broadcastbestpracice;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends BaseaActivity implements View.OnClickListener{

    private EditText editText;
    private Button saveButton;
    private EditText readText;
    private MdatabaseHelper dbHelper;
    private Button addData;
    private Button updateData;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button forceoffline = (Button) findViewById(R.id.force_offline);
        forceoffline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcastbestpracice.FORCE_OFFLINE");
                sendBroadcast(intent);
            }
        });

        editText = (EditText) findViewById(R.id.edit_text);
        String inputS = load();
        //可以判断两种，为null还有为空字符
        if (!TextUtils.isEmpty(inputS)){
            editText.setText(inputS);
            //将输入光标移动到文本的末尾位置
            editText.setSelection(inputS.length());
            Toast.makeText(this, "Restoring successed", Toast.LENGTH_LONG).show();
        }
        saveButton = (Button) findViewById(R.id.save_button);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences("data2", MODE_PRIVATE).edit();
                editor.putString("name", "zhangle");
                editor.putInt("age", 21);
                editor.putBoolean("married", false);
                editor.apply();
                Toast.makeText(MainActivity.this, "Restoring successed", Toast.LENGTH_LONG).show();

            }
        });
        Button readBtn = (Button) findViewById(R.id.read_button);
        readText = (EditText) findViewById(R.id.read_text);
        readBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences preferences = getSharedPreferences("data2", MODE_PRIVATE);
                String name = preferences.getString("name", " ");
                int age = preferences.getInt("age", 0);
                Boolean married = preferences.getBoolean("married", false);
                if (married){
                    readText.setText("我叫" + name + "，今年" + age + "岁，" + "目前已婚");
                }else {
                    readText.setText("我叫" + name + "，今年" + age + "岁，" + "目前未婚");
                }

            }
        });

        dbHelper = new MdatabaseHelper(this, "BookStore.db", null, 2);
        Button createDB = (Button) findViewById(R.id.create_db);
        createDB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper.getWritableDatabase();
            }
        });

        addData = (Button) findViewById(R.id.add_data);
        addData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("name", "The Da Vinci Code");
                values.put("author","Dan Brown");
                values.put("pages", "454");
                values.put("price", 45.32);
                db.insert("Book", null, values);
                values.clear();
                //插入第二条数据
                values.put("name", "The Lost Symbol");
                values.put("author","Dan Brown");
                values.put("pages", "510");
                values.put("price", 45.32);
                db.insert("Book", null, values);
                Toast.makeText(MainActivity.this, "Add successed", Toast.LENGTH_LONG).show();
            }
        });
        updateData = (Button) findViewById(R.id.update_data);
        updateData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("price", 1.2);
                // 第一个参数 表名
                // 第二个参数 要更新的数据
                // 第三、四个参数 用于约束更新某一行或某几行的数据
                // 第三个参数 相当于SQL语句中的where部分， ？表示一个占位符，通过第四个参数提供一个字符串数组为第三个
                // 参数中的每个占位符指定相应的内容
                db.update("Book", values, "name = ?", new String[]{ "The Da Vinci Code"
                });
                Toast.makeText(MainActivity.this, "Update successed", Toast.LENGTH_LONG).show();
            }
        });

        Button deletedb = (Button) findViewById(R.id.delete_data);
        deletedb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                db.delete("Book", "pages > ?", new String[]{"2"});
                Toast.makeText(MainActivity.this, "Delete successed", Toast.LENGTH_LONG).show();
            }
        });

        Button querydb = (Button) findViewById(R.id.query_data);
        querydb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                // 查询Book表中所有的数据
                Cursor cuso = db.query("Book", null, null, null, null, null, null);
                // 数据指针移动到第一行
                if (cuso.moveToFirst()){
                    do {
                        // 遍历Cursor对象，取出数据并打印
                        String name = cuso.getString(cuso.getColumnIndex("name"));
                        String author = cuso.getString(cuso.getColumnIndex("author"));
                        int pages = cuso.getInt(cuso.getColumnIndex("pages"));
                        double price = cuso.getInt(cuso.getColumnIndex("price"));
                        Log.d("MainActivity", "book name is " + name);
                        Log.d("MainActivity", "book author is " + author);
                        Log.d("MainActivity", "book pages is " + pages);
                        Log.d("MainActivity", "book price is " + price);
                    }while (cuso.moveToNext());
                }
                cuso.close();
            }
        });

        Button gotoLitepal = (Button) findViewById(R.id.litepal_btn);
        gotoLitepal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LitepalActivity.class);
                startActivity(intent);
            }
        });

        Button addNotice = (Button)findViewById(R.id.send_notice);
        addNotice.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String input = editText.getText().toString();
        save(input);
    }

    public  void save(String inputStr){
        FileOutputStream outputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            outputStream = openFileOutput("data", MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(inputStr);

        }catch (IOException e){
             e.printStackTrace();
        }finally {
            try {
                if (bufferedWriter != null){
                    bufferedWriter.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }

    public String load(){
        FileInputStream inputStream = null;
        BufferedReader bufferedReader = null;
        StringBuilder content = new StringBuilder();
        try {
            inputStream = openFileInput("data");
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = bufferedReader.readLine())!= null){
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (bufferedReader != null){
                try {
                    bufferedReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.send_notice:
                Intent intent = new Intent(this, LitepalActivity.class);
                PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new NotificationCompat.Builder(this)
                        .setContentTitle("下雨了！！！")
                        .setContentText("你妈叫你回家吃饭") // 超出部分用省略号截断
//                        .setStyle(new NotificationCompat.BigTextStyle().bigText("Learn how to build notifications, send and sync data," +
//                                " and use voice actions. Get the official Android IDE and developer tools to bulid apps for Android"))
                        .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.big_image)))
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(pi)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//                        .setAutoCancel(true) //取消通知
                        .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/luna.ogg"))) // 声音
                        .setVibrate(new long[]{0, 1000, 1000, 1000}) //振动
                        .setLights(Color.GREEN, 1000, 1000) // LED灯闪烁
//                        .setDefaults(NotificationCompat.DEFAULT_ALL) //使用系统默认的效果
                        .setPriority(NotificationCompat.PRIORITY_MAX)  // 最高的优先级
                        .build();
                manager.notify(1, notification);
                break;
            default:
                break;
        }
    }
}
